# url = 'http://tieba.baidu.com/p/2460150866'

'''
https://tieba.baidu.com/p/2460150866?pn=1
https://tieba.baidu.com/p/2460150866?pn=2
https://tieba.baidu.com/p/2460150866?pn=3
'''

import os
from os import path
import requests
from urllib.request import urlretrieve
import re


def get_html(url, page):
    try:
        response = requests.get(url, {'pn': page})
        get_image(response.text, page)
    except Exception as e:
        print(e)


def get_image(code, page):
    global num
    try:
        reg = r'src="(.+?\.jpg)" pic_ext'
        compile = re.compile(reg)
        image_list = re.findall(compile, code)

        if not path.exists('./image'):
            os.mkdir('./image')

        num = 1
        for image_url in image_list:
            urlretrieve(image_url, './image/第%s页%s.jpg' % (page, num))
            num += 1
    except Exception as e:
        print(e)


def get_three_code(url):
    for i in range(1, 4):
        get_html(url, i)


if __name__ == '__main__':
    url = 'https://tieba.baidu.com/p/2460150866'
    get_three_code(url)
